package _8nio;

import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.*;

/**
 * @description:
 * @author: wang zhen
 * @create: 2022-07-12 16:31
 */
public class ServerSocketChannelTest {


    @Test
    public void server() {

        List<SocketChannel> list= new ArrayList();

        ServerSocketChannel serverSocketChannel = null;
        try {

            //创建Server
            serverSocketChannel = ServerSocketChannel.open();

            //绑定端口
            serverSocketChannel.bind(new InetSocketAddress("127.0.0.1", 9999));
            serverSocketChannel.configureBlocking(false);
            System.out.println("开始监听");

            while (true){

                SocketChannel channel = serverSocketChannel.accept();
                if(channel!=null){
                    channel.configureBlocking(false);
                    list.add(channel);
                }


                Iterator<SocketChannel> iterator = list.iterator();
                while (iterator.hasNext()){
                    SocketChannel next = iterator.next();

                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    int len=next.read(buffer);
                    if(len==-1){
                        iterator.remove();
                    }

                    System.out.println(next.getRemoteAddress()+"发送的数据:" + new String(buffer.array())+"数据大小:"+len);
                }

            }



        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            try {
                if (serverSocketChannel != null) {
                    serverSocketChannel.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }



    @Test
    public void client() {

        Socket socket = null;
        OutputStream outputStream = null;
        InputStream inputStream = null;
        try {
            //1.创建客户端对象，并指定连接的IP地址或主机名+端口号
            socket = new Socket("127.0.0.1", 9999);



            //2.获取这个通道的流，输出数据到通道中
            outputStream = socket.getOutputStream();

            //3.发送数据
            outputStream.write("你好".getBytes());
            socket.shutdownOutput();//通过shutdownOutput高速服务器已经发送完数据，后续只能接受数据


        } catch (Exception e) {
            e.printStackTrace();

        } finally {

            //5.关闭资源
            try {
                if (inputStream != null) {
                    inputStream.close();
                }

                if (outputStream != null) {
                    outputStream.close();
                }

                if (socket != null) {
                    socket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
